package com.koocloud.electroplatemanage.configuration;

import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 根据浏览器的安全保护规则，跨域的时候创建的sessionId是不会被浏览器保存下来的，
 * 也就是说，每一次的请求，服务器就会以为是一个新的人，而不是同一个人，
 */
@Configuration
public class CorsFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest reqs = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.setHeader("Access-Control-Expose-Headers", "*");
        /**
         * 对应客户端的 xhrFields.withCredentials: true ，服务器端通过在响应 header 中设置
         * Access-Control-Allow-Credentials = true 来运行客户端携带证书式访问。 通过对 Credentials
         * 参数的设置，就可以保持跨域 Ajax 时的 Cookie。
         */
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}
